package com.wqj.kyee.gps.nav

import android.annotation.SuppressLint
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.location.Location
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewTreeObserver
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.navi.AMapNavi
import com.amap.api.navi.AMapNaviListener
import com.amap.api.navi.AMapNaviView
import com.amap.api.navi.enums.NaviType
import com.amap.api.navi.model.*
import com.amap.api.navi.view.PoiInputItemWidget
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.PoiItem
import com.amap.api.services.geocoder.GeocodeQuery
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.poisearch.PoiResult
import com.amap.api.services.poisearch.PoiSearch
import com.autonavi.tbt.TrafficFacilityInfo
import com.wqj.kyee.gps.R
import com.wqj.kyee.gps.bluetooth.BtDevicesActivity
import com.wqj.kyee.gps.bluetooth.BtReadThread
import com.wqj.kyee.gps.nmea.NMEA
import com.wqj.kyee.gps.ui.SearchActivity
import com.wqj.kyee.gps.util.*
import kotlinx.android.synthetic.main.activity_route_select.*
import org.jetbrains.anko.backgroundColor
import org.jetbrains.anko.find
import java.lang.ref.WeakReference
import java.util.*


class RouteSelectActivity : AppCompatActivity(), AMapNaviListener, TextView.OnEditorActionListener
        , PoiSearch.OnPoiSearchListener, TextWatcher, View.OnTouchListener
        , GeocodeSearch.OnGeocodeSearchListener, View.OnClickListener
        , AdapterView.OnItemClickListener, ViewTreeObserver.OnGlobalLayoutListener {
    override fun onCalculateRouteSuccess(p0: AMapCalcRouteResult?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onCalculateRouteFailure(p0: AMapCalcRouteResult?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onNaviRouteNotify(p0: AMapNaviRouteNotifyData?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    lateinit var mMapView: AMapNaviView
    lateinit var mAMapNavi: AMapNavi
    lateinit var mTtsManager: TTSController
    lateinit var aMap: AMap
    lateinit var startNavView: Button
    lateinit var backView: TextView
    lateinit var poiResult: PoiResult
    lateinit var query: PoiSearch.Query
    var mode: Int = NORMAL
    var poiCurrentPage: Int = 1
    var poiNames: MutableList<String> = ArrayList()
    var loadingDialog: MyLoadingDialog = MyLoadingDialog()

    var mEndLatlng = NaviLatLng(31.2166865743, 121.6271389919)
    var mStartLatlng = NaviLatLng(MapActivity.curLat, MapActivity.curLng)
    lateinit var mStartMarker : Marker
    lateinit var mEndMarker : Marker

    val startList: MutableList<NaviLatLng> = ArrayList()
    val endList: MutableList<NaviLatLng> = ArrayList()
    var sPointViewComplete = false
    var ePointViewComplete = false
    var mWayPointList: MutableList<NaviLatLng> = ArrayList()
    lateinit var autoCompleteAdapter: ArrayAdapter<String>
    lateinit var geocoderSearch:GeocodeSearch
    lateinit var btReadThread: BtReadThread
    var car_number: String? = null

    var congestion : Boolean = false
    var cost : Boolean = false
    var hightspeed : Boolean = false
    var avoidhightspeed : Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_route_select)

        supportActionBar?.hide()

        startNavView = find<Button>(R.id.startNavView)
        mMapView = find<AMapNaviView>(R.id.mapView)
        mMapView.onCreate(savedInstanceState);
        aMap = mMapView.getMap()
        mAMapNavi = AMapNavi.getInstance(applicationContext)
        mAMapNavi.addAMapNaviListener(this)
        mAMapNavi.setIsUseExtraGPSData(true)

        val options = mMapView.viewOptions
        options.isLayoutVisible = false
        options.isAutoDrawRoute = false
        options.isTrafficLine = true
        options.isTrafficInfoUpdateEnabled = true
        // options.isRouteListButtonShow = true
        options.setLeaderLineEnabled(1)
        mMapView.viewOptions = options
        mMapView.naviMode = AMapNaviView.CAR_UP_MODE
        geocoderSearch = GeocodeSearch(this)
        geocoderSearch.setOnGeocodeSearchListener(this)
        car_number = getCarNumber()
        if (car_number != null) {
            var carInfo = AMapCarInfo()
            carInfo.carNumber = car_number
            carInfo.isRestriction = MapActivity.isRestrict
            mAMapNavi.setCarInfo(carInfo)
        }
        mTtsManager = TTSController.getInstance(getApplicationContext());
        mTtsManager.init()
        mAMapNavi.addAMapNaviListener(mTtsManager)

        var tmpLatLng = LatLng(MapActivity.curLat, MapActivity.curLng)
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(tmpLatLng, 10f))
        //取得从上一个Activity当中传递过来的Intent对象

        mStartMarker = aMap.addMarker(MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.start_point))).anchor(0.5f, 0.5f))
        mEndMarker = aMap.addMarker(MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.end_point))).anchor(0.5f, 0.5f))
        mStartMarker.position = LatLng(mStartLatlng.latitude, mStartLatlng.longitude)
        //startList.clear()
        //startList.add(mStartLatlng)

        val intent = getIntent()
        //从Intent当中根据key取得value
        if (intent != null) {
            // 上个页面传来的目的地
            var lat = intent.getDoubleExtra("lat", 0.0)
            var lng = intent.getDoubleExtra("lng", 0.0)
            var title = intent.getStringExtra("title")
            ePointView.setText(title)
            mEndLatlng = NaviLatLng(lat, lng)
            mEndMarker.position = LatLng(mEndLatlng.latitude, mEndLatlng.longitude)
            //endList.clear()
            //endList.add(mEndLatlng)
            Log.d("wqj", "start avoid congestion")
            if (lat != 0.0 && lng != 0.0) {
                //way1View.backgroundColor = ContextCompat.getColor(this, R.color.colorConnBtBtnBkg)
                //startCalculateRoute(AVOID_CONGESTION)
                calculateRoute()
            }
        } else {
            ePointView.setText("")
        }
        //sPointView.setOnEditorActionListener(this)
        //ePointView.setOnEditorActionListener(this)
        // sPointView.setOnTouchListener(this)
        //sPointView.addTextChangedListener(this)
        //ePointView.addTextChangedListener(this)

        // 点击auto complete text的item后
        //sPointView.setOnItemClickListener(this)
        //ePointView.setOnItemClickListener(this)

        startNavView.setOnClickListener(this)
        way1View.setOnClickListener(this)
        way2View.setOnClickListener(this)
        way3View.setOnClickListener(this)
        way4View.setOnClickListener(this)

        sPointView.setOnClickListener(this)
        ePointView.setOnClickListener(this)

        mMapView.getViewTreeObserver().addOnGlobalLayoutListener(this)
        btReadThread = BtReadThread(MyHandler(this))
    }

    override fun showLaneInfo(p0: AMapLaneInfo?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun updateIntervalCameraInfo(p0: AMapNaviCameraInfo?, p1: AMapNaviCameraInfo?, p2: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onItemClick(a: AdapterView<*>?, v: View?, c: Int, d: Long) {

        if (sPointView.isFocused) {
                sPointViewComplete = true
                mStartLatlng = NaviLatLng(poiItemList[c].latLonPoint.latitude
                        ,poiItemList[c].latLonPoint.longitude)
                sPointView.dismissDropDown()
                hideSoftKeyBoard(sPointView)
                if (sPointView.text.toString() != "" && ePointView.text.toString() != "") {
                    startCalculateRoute(AVOID_CONGESTION)
                }
                Log.d("wqj", "on clicked: ")
            }
            else if (ePointView.isFocused){
                ePointViewComplete = true
                mEndLatlng = NaviLatLng(poiItemList[c].latLonPoint.latitude
                        ,poiItemList[c].latLonPoint.longitude)
                ePointView.dismissDropDown()
                hideSoftKeyBoard(ePointView)
                if (sPointView.text.toString() != "" && ePointView.text.toString() != "") {
                    // 开始计算导航路线
                    //startCalculateRoute(AVOID_CONGESTION)
                }
            }
    }

    fun quitNav(v: View) {
        mAMapNavi.stopNavi()
        quitLayout.visibility = View.GONE
        setActivityMode(NORMAL)
    }

    fun cancelQuitNav(v: View) {
        quitLayout.visibility = View.GONE
    }

    fun wayBtnChecked(v: TextView) {
        if (sPointView.text.toString() == "" || ePointView.text.toString() == "") {
            return
        }
        way1View.backgroundColor = ContextCompat.getColor(this, R.color.white)
        way2View.backgroundColor = ContextCompat.getColor(this, R.color.white)
        way3View.backgroundColor = ContextCompat.getColor(this, R.color.white)
        way4View.backgroundColor = ContextCompat.getColor(this, R.color.white)
        v.backgroundColor = ContextCompat.getColor(this, R.color.colorConnBtBtnBkg)
    }

    var mapHeight: Int = 0
    override fun onGlobalLayout() {
        Log.d("wqj", "layout changed: " + mMapView.height)
//        var currHeight = mMapView.height
//
//        if (mapHeight == 0) {
//            mapHeight = currHeight
//            return
//        }
//        if (currHeight < mapHeight) {
//            //Handler().postDelayed({
//            EnterPotEditMode(true)
//            //}, 100)
//
//        } else {
//            Handler().postDelayed({
//                EnterPotEditMode(false)
//            }, 200)
//
//        }

    }

//    fun EnterPotEditMode(flag: Boolean) {
//        if (flag) {
//            Log.d("wqj", "comp gone")
//            mMapView.alpha = 0f
//            selectLayout.alpha = 0f
//            startNavView.alpha = 0f
//            revertView.alpha = 0f
//            if (sPointView.isFocused) {
//                endPosLayout.visibility = View.GONE
//            } else if (ePointView.isFocused) {
//                myPosLayout.visibility = View.GONE
//            }
//
//            var lp = myPosLayout.layoutParams as RelativeLayout.LayoutParams
//            lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, 1)
//            lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1)
//            myPosLayout.layoutParams = lp
//
//
//        } else {
//            Log.d("wqj", "comp visible")
//            mMapView.alpha = 1f
//            selectLayout.alpha = 1f
//            startNavView.alpha = 1f
//            revertView.alpha = 1f
//            if (sPointView.isFocused) {
//                endPosLayout.visibility = View.VISIBLE
//            } else if (ePointView.isFocused) {
//                myPosLayout.visibility = View.VISIBLE
//            }
//            var lp = myPosLayout.layoutParams as RelativeLayout.LayoutParams
//            lp.removeRule(RelativeLayout.ALIGN_PARENT_LEFT)
//            lp.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT)
//            myPosLayout.layoutParams = lp
//
//        }
//    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.way1View -> {
                startCalculateRoute(AVOID_CONGESTION)
                //wayBtnChecked(way1View)
            }
            R.id.way2View -> {
                startCalculateRoute(AVOID_COST)
                //wayBtnChecked(way2View)
            }
            R.id.way3View -> {
                startCalculateRoute(AVOID_HIGH_WAY)
                //wayBtnChecked(way3View)
            }
            R.id.way4View -> {
                startCalculateRoute(HIGH_WAY_FIRST)
                //wayBtnChecked(way4View)
            }
            R.id.sPointView -> {
                var intent = Intent(this, SearchActivity::class.java)
                intent.putExtra(BaseTransitionInActivity.EXTRA_TRANSITION, BaseTransitionInActivity.TRANSITION_FADE_FAST)
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, MapActivity.curCity)
                intent.putExtra(Constants.EXTRA_HINT, "输入起点")
                intent.putExtra(Constants.EXTRA_POINTTYPE, PoiInputItemWidget.TYPE_START)
                startActivityWithOptions(intent, Constants.SEARCH_START_REQUEST_CODE)
            }
            R.id.ePointView -> {
                var intent = Intent(this, SearchActivity::class.java)
                intent.putExtra(BaseTransitionInActivity.EXTRA_TRANSITION, BaseTransitionInActivity.TRANSITION_FADE_FAST)
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, MapActivity.curCity)
                intent.putExtra(Constants.EXTRA_HINT, "输入终点")
                intent.putExtra(Constants.EXTRA_POINTTYPE, PoiInputItemWidget.TYPE_DEST)
                startActivityWithOptions(intent, Constants.SEARCH_END_REQUEST_CODE)
            }
            R.id.startNavView -> {
                setActivityMode(NAVING)
                //mAMapNavi.setEmulatorNaviSpeed(75)
                //mAMapNavi.startNavi(NaviType.EMULATOR)
                mAMapNavi.startNavi(NaviType.GPS)
            }
        }
    }

    @SuppressLint("RestrictedApi")
    fun startActivityWithOptions(intent : Intent, requestCode: Int) {
        var transitionActivity = ActivityOptions.makeSceneTransitionAnimation(this);
        //startActivity(intent, transitionActivity.toBundle())
        startActivityForResult(intent, requestCode, transitionActivity.toBundle())
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Constants.SEARCH_LOCATION_RESULT_CODE) {
            var poi = data?.getParcelableExtra<Poi>(Constants.EXTRA_POI);

            if (requestCode == Constants.SEARCH_START_REQUEST_CODE) {
                sPointView.setText(poi?.name)
                mStartLatlng = NaviLatLng(poi?.coordinate!!.latitude, poi?.coordinate.longitude)
                mStartMarker.position = LatLng(poi?.coordinate!!.latitude, poi?.coordinate.longitude)

                //startList.clear()
                //startList.add(mStartLatlng)

            } else if (requestCode == Constants.SEARCH_END_REQUEST_CODE) {
                ePointView.setText(poi?.name)

                mEndLatlng = NaviLatLng(poi?.coordinate!!.latitude, poi?.coordinate.longitude)
                mEndMarker.position = LatLng(poi?.coordinate!!.latitude, poi?.coordinate.longitude)

                //endList.clear()
                //endList.add(mEndLatlng)
            }
        }
    }

    fun setActivityMode(m: Int) {
        var lp: RelativeLayout.LayoutParams = mMapView.layoutParams as RelativeLayout.LayoutParams

        mode = m
        when (mode) {
            NORMAL -> {
                startNavView.visibility = View.VISIBLE
                selectLayout.visibility = View.VISIBLE
                val options = mMapView.viewOptions
                options.isLayoutVisible = false
                mMapView.viewOptions = options
                lp.removeRule(RelativeLayout.ALIGN_PARENT_TOP)
                lp.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
                lp.addRule(RelativeLayout.BELOW, R.id.endPosLayout)
                lp.addRule(RelativeLayout.ABOVE, R.id.selectLayout)
            }
            NAVING -> {
                startNavView.visibility = View.GONE
                selectLayout.visibility = View.GONE
                val options = mMapView.viewOptions
                options.isLayoutVisible = true
                mMapView.viewOptions = options
                lp.removeRule(RelativeLayout.BELOW)
                lp.removeRule(RelativeLayout.ABOVE)
                lp.addRule(RelativeLayout.ALIGN_PARENT_TOP)
                lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
            }
        }
    }

    public class MyHandler(activity: RouteSelectActivity) : Handler() {

        //对Activity的弱引用
        private val mActivity: WeakReference<RouteSelectActivity>
        init {
            mActivity = WeakReference<RouteSelectActivity>(activity)
        }
        override fun handleMessage(msg: Message) {
            val activity = mActivity.get()
            if (activity == null) {
                super.handleMessage(msg)
                return
            }
            when (msg.what) {
                BtDevicesActivity.GPS_BOARD_DATA -> {
                    var data: NMEA.GPSPosition = msg.obj as NMEA.GPSPosition
                    //var content = MainActivity.ByteArrayToHexString(data.buffer, data.size)
                    //var text = "获取到蓝牙板数据: " + content
                    //Toast.makeText(activity, text, Toast.LENGTH_SHORT).show()
                    // 读取gps板定位数据并显示在地图上
                    val location = Location("bt-gps")
                    location.setLongitude(data.lon)
                    location.setLatitude(data.lat)
                    location.setSpeed(data.velocity)
                    location.setAccuracy(2.5f)
                    location.setBearing(data.dir)
                    location.setTime(System.currentTimeMillis())
                    activity.mAMapNavi.setExtraGPSData(1, location)

                }
                else -> super.handleMessage(msg)
            }
        }
    }

    override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {
        if (p0?.id == R.id.sPointView) {
            var v = p0 as AutoCompleteTextView
            if ("我的位置".contains(v.text)) {
                v.setText("")
            }
        }
        var imm = p0?.getContext()?.getSystemService(Context.INPUT_METHOD_SERVICE)
                as InputMethodManager
        if(imm.isActive()) {
            imm.hideSoftInputFromWindow(p0.getApplicationWindowToken(), 1)
        }
        return true

    }

    override fun afterTextChanged(p0: Editable?) {
        Log.d("wqj", "after changed: ")
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        Log.d("wqj", "before changed: " + p0)
    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        if (p0?.length == 0) {
            return
        }
        if ((!sPointViewComplete && sPointView.isFocused)
                || (!ePointViewComplete && ePointView.isFocused)) {
            poiSearch(p0.toString())
        }
        else {
            sPointViewComplete = false
            ePointViewComplete = false
        }

    }

    override fun onRegeocodeSearched(p0: RegeocodeResult?, p1: Int) {

    }

    override fun onGeocodeSearched(result: GeocodeResult?, rCode: Int) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getGeocodeAddressList() != null
                    && result.getGeocodeAddressList().size > 0) {
                val address = result.getGeocodeAddressList().get(0)
                var point = address.getLatLonPoint()
                val addressName = ("经纬度值:" + address.getLatLonPoint() + "\n位置描述:"
                        + address.getFormatAddress())
                if (sPointView.isFocused) {
                    mStartLatlng = NaviLatLng(point.latitude, point.longitude)
                } else if (ePointView.isFocused) {
                    mEndLatlng = NaviLatLng(point.latitude, point.longitude)
                }
                if (sPointView.text.toString() != "" && ePointView.text.toString() != "") {
                    startCalculateRoute(AVOID_CONGESTION)
                }
                //ToastUtil.show(this@MapActivity, addressName)
            } else {
                //ToastUtil.show(this@MapActivity, R.string.no_result)
            }
        } else {
            ToastUtil.showerror(this, rCode)
        }
    }


    override fun onPoiItemSearched(p0: PoiItem?, p1: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    var poiItemList: ArrayList<PoiItem> = arrayListOf()
    override fun onPoiSearched(result: PoiResult?, rCode: Int) {
        dismissDialog()
        Log.d("wqj", "poi searched")
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.query != null) {
                poiResult = result
                if (true) {
                    Log.d("wqj", result.pois[0].title)
                    var poiItems: List<PoiItem> = result.pois
                    if (poiItems != null && poiItems.size > 0) {
                        poiNames.clear()
                        poiItems.forEach {
                            poiItemList.add(it)
                            poiNames.add(it.title)
                        }
                        autoCompleteAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, poiNames)
                        if (sPointView.isFocused) {

                            if (!sPointViewComplete) {
                                sPointView.setAdapter(autoCompleteAdapter)
                                sPointView.showDropDown()
                                Log.d("wqj", "sp drop down")
                            } else {
                                sPointViewComplete = false
                            }
                        } else if (ePointView.isFocused) {
                            if (!ePointViewComplete) {
                                ePointView.setAdapter(autoCompleteAdapter)
                                ePointView.showDropDown()
                                Log.d("wqj", "ep drop down")
                            } else {
                                ePointViewComplete = false
                            }
                        }
                    } else {
                        ToastUtil.show(this, "没有找到相关poi信息")
                    }
                }
            } else {
                ToastUtil.show(this, "没有找到相关poi信息")
            }
        } else {
            ToastUtil.showerror(this, rCode)
        }
    }

    // poi检索
    fun poiSearch(text: String) {
        if (text.length == 0) {
            return
        }
        query = PoiSearch.Query(text, "", MapActivity.curCity)
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(poiCurrentPage);//设置查询页码

        var poiSearch = PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    // 地址到坐标的转换
    fun potSearch(text: String) {
        // name表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode
        val query = GeocodeQuery(text, MapActivity.curCity);
        geocoderSearch.getFromLocationNameAsyn(query);
    }

    override fun onDestroy() {
        super.onDestroy()
        mMapView.onDestroy()
        mAMapNavi.removeAMapNaviListener(this)
        mAMapNavi.removeAMapNaviListener(mTtsManager)
        mTtsManager.destroy()
        mAMapNavi.destroy()
        btReadThread.cancel()
    }

    override fun onResume() {
        super.onResume()
        mMapView.onResume()
        mAMapNavi.resumeNavi()
        btReadThread.start()
    }

    override fun onPause() {
        super.onPause()
        mAMapNavi.stopNavi()
        mMapView.onPause()
        mTtsManager.stopSpeaking()
        mAMapNavi.pauseNavi()
        btReadThread.cancel()
    }

    override fun onStop() {
        super.onStop()
        mAMapNavi.stopNavi()
        btReadThread.cancel()
    }

    override fun onStart() {
        super.onStart()
        btReadThread.start()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {

        if (mode == NAVING) {
            when (keyCode) {
                KeyEvent.KEYCODE_BACK -> {
                    // mAMapNavi.stopNavi()
                    when (quitLayout.visibility) {
                        View.GONE -> quitLayout.visibility = View.VISIBLE
                        View.VISIBLE -> quitLayout.visibility = View.GONE
                    }
                    return true
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        Log.d("wqj", "hello searched: " + actionId)
        if(actionId == EditorInfo.IME_NULL) {
            // 隐藏软件盘
            hideSoftKeyBoard(v)
            when (v?.id) {
                R.id.sPointView -> {
                    potSearch(v.text.toString())
                    sPointView.dismissDropDown()
                    sPointViewComplete = true
                }
                R.id.ePointView -> {
                    potSearch(v.text.toString())
                    ePointView.dismissDropDown()
                    ePointViewComplete = true
                }
            }
        }
        return true
    }

    fun hideSoftKeyBoard(v: TextView?) {
        // 隐藏软件盘
        var imm = v?.getContext()?.getSystemService(Context.INPUT_METHOD_SERVICE)
                as InputMethodManager
        if(imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0)
        }
    }

    fun showDialog() {
        //loadingDialog?.show(getFragmentManager(), "Loading")
    }

    fun dismissDialog() {
        //loadingDialog?.dismiss()
    }

    fun calculateRoute() {
        var strategyFlag: Int = 0

        try {
            strategyFlag = mAMapNavi.strategyConvert(congestion, avoidhightspeed, cost, hightspeed, true)
        } catch (e : Exception) {
            e.printStackTrace()
        }

        if (strategyFlag >= 0) {
            startList.clear()
            endList.clear()

            startList.add(mStartLatlng)
            endList.add(mEndLatlng)

            mAMapNavi.calculateDriveRoute(startList, endList, mWayPointList, strategyFlag)

            ToastUtil.show(applicationContext, "Strategy: " + strategyFlag)
        }
    }

    fun startCalculateRoute(type: Int) {
        /**
         * 方法: int strategy=mAMapNavi.strategyConvert(congestion, avoidhightspeed, cost, hightspeed, multipleroute); 参数:
         *
         * @congestion 躲避拥堵
         * @avoidhightspeed 不走高速
         * @cost 避免收费
         * @hightspeed 高速优先
         * @multipleroute 多路径
         *
         * 说明: 以上参数都是boolean类型，其中multipleroute参数表示是否多条路线，如果为true则此策略会算出多条路线。
         * 注意: 不走高速与高速优先不能同时为true 高速优先与避免收费不能同时为true
         */
        var strategy = 0
        var avoidCongestion = false
        var avoidHighWay = false
        var avoidCost = false
        var highWayFirst = false
        if (sPointView.text.toString() == "" || ePointView.text.toString() == "") {
            ToastUtil.show(this, "请先完善起点和终点信息")
        }

        try {
            //再次强调，最后一个参数为true时代表多路径，否则代表单路径
            when (type) {
                AVOID_CONGESTION -> {
                    avoidCongestion = true
                    wayBtnChecked(way1View)
                }
                AVOID_HIGH_WAY -> {
                    avoidHighWay = true
                    wayBtnChecked(way3View)
                }
                AVOID_COST -> {
                    avoidCost = true
                    wayBtnChecked(way2View)
                }
                HIGH_WAY_FIRST -> {
                    highWayFirst = true
                    wayBtnChecked(way4View)
                }
            }
            strategy = mAMapNavi.strategyConvert(avoidCongestion, avoidHighWay, avoidCost, highWayFirst, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        startList.clear()
        endList.clear()
        startList.add(mStartLatlng)
        endList.add(mEndLatlng)
        mAMapNavi.calculateDriveRoute(startList, endList, mWayPointList, strategy)
    }

    override fun onInitNaviSuccess() {
        // startCalculateRoute(AVOID_CONGESTION)
    }

    override fun onCalculateRouteSuccess(ids: IntArray) {
        Log.d("wqj", "id")
        //mMapView.displayOverview()
        //mAMapNavi.setEmulatorNaviSpeed(75)
        //mAMapNavi.startNavi(NaviType.EMULATOR)


        //        如果根据获取的导航路线来自定义绘制
        /*
        val routeOverlay = RouteOverLay(aMap, mAMapNavi.naviPath, this)
        routeOverlay.setStartPointBitmap(BitmapFactory.decodeResource(this.resources, R.drawable.dir_start))
        routeOverlay.setEndPointBitmap(BitmapFactory.decodeResource(this.resources, R.drawable.dir_end))
        routeOverlay.setWayPointBitmap(BitmapFactory.decodeResource(this.resources, R.drawable.dir_station))
        routeOverlay.setTrafficLine(false)
        try {
            routeOverlay.width = 30f
        } catch (e: AMapNaviException) {
            //宽度须>0
            e.printStackTrace()
        }

        val color = IntArray(10)
        color[0] = Color.BLACK
        color[1] = Color.RED
        color[2] = Color.BLUE
        color[3] = Color.YELLOW
        color[4] = Color.GRAY
        routeOverlay.addToMap(color, mAMapNavi.naviPath.getWayPointIndex())
        routeOverlay.zoomToSpan()
        */
//        routeOverlay.addToMap();
    }

    override fun showLaneInfo(laneInfos: Array<AMapLaneInfo>, laneBackgroundInfo: ByteArray, laneRecommendedInfo: ByteArray) {
        val sb = StringBuffer()
        sb.append("共" + laneInfos.size + "车道")
        for (i in laneInfos.indices) {
            val info = laneInfos[i]
            //当前车道可以选择的动作
            val background = info.laneTypeIdHexString[0]
            //当前用户要执行的动作
            val Recommend = info.laneTypeIdHexString[1]
            //根据文档中每个动作对应的枚举类型，显示对应的图片
            try {
                sb.append("，第" + (i + 1) + "车道为" + array[getHex(background)] + "，该车道可执行动作为" + actions[getHex(Recommend)])
            } catch (e: Exception) {
                e.printStackTrace()
            }

        }
        // Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show()
    }

    fun onBackClick(view: View) {
        this.finish()
    }

    var array = arrayOf("直行车道", "左转车道", "左转或直行车道", "右转车道", "右转或这行车道", "左掉头车道", "左转或者右转车道", " 左转或右转或直行车道", "右转掉头车道", "直行或左转掉头车道", "直行或右转掉头车道", "左转或左掉头车道", "右转或右掉头车道", "无", "无", "不可以选择该车道")

    var actions = arrayOf("直行", "左转", "左转或直行", "右转", "右转或这行", "左掉头", "左转或者右转", " 左转或右转或直行", "右转掉头", "直行或左转掉头", "直行或右转掉头", "左转或左掉头", "右转或右掉头", "无", "无", "不可以选择")
    override fun hideLaneInfo() {}

    //计算16进制对应的数值
    @Throws(Exception::class)
    fun getHex(ch: Char): Int {
        if (ch >= '0' && ch <= '9')
            return (ch - '0').toInt()
        if (ch >= 'a' && ch <= 'f')
            return (ch - 'a' + 10).toInt()
        if (ch >= 'A' && ch <= 'F')
            return (ch - 'A' + 10).toInt()
        throw Exception("error param")
    }

    override fun onNaviInfoUpdate(p0: NaviInfo?) {

    }

    override fun onCalculateRouteFailure(p0: Int) {

    }

    override fun onServiceAreaUpdate(p0: Array<out AMapServiceAreaInfo>?) {

    }

    override fun onEndEmulatorNavi() {

    }

    override fun onArrivedWayPoint(p0: Int) {

    }

    override fun onArriveDestination() {

    }

    override fun onPlayRing(p0: Int) {

    }

    override fun onTrafficStatusUpdate() {

    }

    override fun onGpsOpenStatus(p0: Boolean) {

    }

    override fun updateAimlessModeCongestionInfo(p0: AimLessModeCongestionInfo?) {

    }

    override fun showCross(p0: AMapNaviCross?) {

    }

    override fun onGetNavigationText(p0: Int, p1: String?) {

    }

    override fun onGetNavigationText(p0: String?) {

    }

    override fun updateAimlessModeStatistics(p0: AimLessModeStat?) {

    }

    override fun hideCross() {

    }

    override fun onInitNaviFailure() {

    }

    override fun onReCalculateRouteForTrafficJam() {

    }

    override fun onNaviInfoUpdated(p0: AMapNaviInfo?) {

    }

    override fun showModeCross(p0: AMapModelCross?) {

    }

    override fun updateCameraInfo(p0: Array<out AMapNaviCameraInfo>?) {

    }

    override fun hideModeCross() {

    }

    override fun onLocationChange(p0: AMapNaviLocation?) {

    }

    override fun onReCalculateRouteForYaw() {

    }

    override fun onStartNavi(p0: Int) {

    }

    override fun notifyParallelRoad(p0: Int) {

    }

    override fun OnUpdateTrafficFacility(p0: AMapNaviTrafficFacilityInfo?) {

    }

    override fun OnUpdateTrafficFacility(p0: Array<out AMapNaviTrafficFacilityInfo>?) {

    }

    override fun OnUpdateTrafficFacility(p0: TrafficFacilityInfo?) {

    }

    fun storeCarNumber(number: String) {
        var sp = getSharedPreferences("carInfo", MODE_PRIVATE)
        var editor = sp.edit()

        editor.putString("carNum", number)

        editor.commit()
    }

    fun getCarNumber():String? {
        var sp = getSharedPreferences("carInfo", MODE_PRIVATE)

        return sp.getString("carInfo", null)
    }

    companion object {
        val AVOID_CONGESTION: Int = 0
        val AVOID_HIGH_WAY: Int = 1
        val AVOID_COST: Int = 2
        val HIGH_WAY_FIRST: Int = 3
        val NAVING: Int = 4
        val NORMAL: Int = 5
    }
}
